<template>
    <div class="mod-prod-info release-goods">
        <div class="title">{{ dataForm.spuId ? '编辑商品信息' : '发布新商品' }}</div>
        <el-form ref="dataForm" class="part-form" :model="dataForm" :rules="rules" label-width="110px">
            <div class="info-box">

                <!-- 1.商品基本信息 -->
                <div class="part-content">
                    <div class="part-tit"><span class="part-tit-num">1</span><span class="part-tit-name">商品基本信息</span></div>
                    <!-- 商品平台分类（不可修改） -->
                    <div class="part-form-div">
                        <div class="part-form-item-tit star">平台分类</div>
                        <div class="part-form-item">
                            <div class="classify-show">
                                <category-group :selected-categorys="selectedCategorys"
                                    :show-category-select-btn="showCategorySelectBtn" :single="true"
                                    @selectOrReviseCategory="selectOrReviseCategory('platform')" />
                                <div v-if="!dataForm.categoryId" class="warning">请先选择分类再填写以下商品信息！</div>
                            </div>
                            <category-selector v-if="categorySelectorVisible" ref="categorySelector"
                                @getCategorySelected="getCategorySelected" />
                        </div>
                    </div>

                    <!-- 商品店铺分类 -->
                    <div class="part-form-div">
                        <div class="part-form-item-tit star">店铺分类</div>
                        <div class="part-form-item">
                            <div class="classify-show">
                                <category-group :selected-categorys="selectedShopCategorys"
                                    :show-category-select-btn="showShopCategorySelectBtn" :single="true"
                                    @selectOrReviseCategory="selectOrReviseCategory('shop')" />
                                <div v-if="!dataForm.categoryId || !dataForm.shopCategoryId" class="warning">
                                    请先选择分类再填写以下商品信息！</div>
                            </div>
                            <category-selector v-if="shopcategorySelectorVisible" ref="shopCategorySelector"
                                @getCategorySelected="getShopCategorySelected" />
                        </div>
                    </div>

                    <!-- 商品标题 -->
                    <el-form-item label="商品标题" prop="name">
                        <el-input v-model.trim="dataForm.name" placeholder="商品标题组成：商品描述+属性" :disabled="!dataForm.categoryId"
                            style="width:90%" />
                    </el-form-item>
                    <!-- 商品卖点 -->
                    <el-form-item label="商品卖点" prop="sellingPoint">
                        <el-input v-model.trim="dataForm.sellingPoint" type="textarea" placeholder="商品卖点"
                            :disabled="!dataForm.categoryId" style="width:90%" />
                    </el-form-item>
                    <!-- 商品品牌 -->
                    <el-form-item label="所属品牌">
                        <div class="brand">
                            <img v-if="brandImgUrl" :src="brandImgUrl" class="brand-img">
                            <el-tag v-if="brandName" class="br" :disable-transitions="true" closable
                                @close="handleCloseBrand()">
                                <span class="brandname">{{ brandName }}</span>
                            </el-tag>
                            <el-button type="text" :class="['sel-brand', dataForm.categoryId ? '' : 'gray']"
                                @click="brandSelectHandle">{{ brandName ? '修改' : '选择' }}品牌</el-button>
                        </div>
                        <brand-selector v-if="brandSelectVisible" ref="brandSelect" :is-single="true"
                            @refreshSelectBrand="selectBrand" />
                    </el-form-item>
                    <!-- 商品基本属性 -->
                    <el-form-item v-if="basicAttrs.length > 0" label="基本属性">
                        <div class="text">请准确填写属性，有利于商品在搜索和推荐中露出，错误填写可能面临商品下架或流量损失！（注：带<span class="stars-icon" />为重要属性，必填）
                        </div>
                        <spu-category-attrs :attrs-list="basicAttrs" @getValueOfBasicAttrs="getValueOfBasicAttrs" />
                    </el-form-item>
                    <!-- 商品排序 -->
                    <el-form-item label="商品排序">
                        <el-input v-model.number="dataForm.seq" :max="32767"
                            oninput="value=value.replace(/^\.+|[^\d.]/g,'')" placeholder="请输入商品排序" :min="1" validate-event
                            style="width:200px" />
                    </el-form-item>
                    <!-- 商品主图 -->
                    <div class="part-form-div">
                        <div class="part-form-item-tit star">商品主图</div>
                        <div class="part-form-item">
                            <img-upload v-model="dataForm.mainImgUrl" />
                        </div>
                    </div>
                    <!-- 商品轮播图 -->
                    <div class="part-form-div">
                        <div class="part-form-item-tit star">商品轮播图</div>
                        <div class="part-form-item">
                            <imgs-upload v-model="dataForm.imgUrls" />
                            <div class="banner-tips">建议图片尺寸为 800*800，可拖动排序，最多上传9张</div>
                        </div>
                    </div>
                </div>

                <!-- 2.商品sku与库存 -->
                <div class="part-content">
                    <div class="part-tit"><span class="part-tit-num">2</span><span class="part-tit-name">商品销售属性与库存</span>
                    </div>
                    <div class="part-form-div">
                        <div class="part-form-item-tit">销售属性</div>
                        <div class="part-form-item">
                            <div class="part-tips">最多添加两个商品属性，第一个商品属性可添加属性图片</div>
                            <!-- sku-组件 -->
                            <sku-block v-model="salesAttrs" ref="skuBlock" :skuAttrs="originalSalesAttrs" />
                            <!-- :is-category-id="dataForm.categoryId ? true : false" -->
                        </div>
                    </div>
                    <!-- 价格及库存 -->
                    <div class="part-form-div">
                        <div class="part-form-item-tit star">价格及库存</div>
                        <div class="setup-spec">
                            <div class="imp-tips">请如实填写库存信息，以确保商品可以在承诺发货时间内发出，避免可能的物流违规</div>
                            <div class="sku-table">
                                <!-- sku表格 -->
                                <sku-table v-model="dataForm.skuList" :data="salesAttrs" :spu-id="parseInt(dataForm.spuId)"
                                    :is-category-id="dataForm.shopCategoryId ? true : false" />
                            </div>
                        </div>
                    </div>
                    <div class="part-form-div">
                        <div class="part-form-item-tit">
                            总库存
                            <el-tooltip class="item" effect="light" content="每个属性库存的总和" placement="top">
                                <i class="el-icon-question" />
                            </el-tooltip>
                        </div>
                        <el-input v-model="dataForm.totalStock" :readonly="true" style="width:150px" />
                    </div>
                </div>

                <!-- 3.商品详情 -->
                <div class="part-content">
                    <div class="part-tit"><span class="part-tit-num">3</span><span class="part-tit-name">商品详情</span></div>
                    <div class="part-form-info">
                        <!-- 商品详情图 -->
                        <div class="part-form-div">
                            <div class="part-form-item-tit star">商品详情</div>
                            <div class="part-form-item">
                                <imgs-upload v-model="dataForm.detail" />
                                <div class="banner-tips">建议图片尺寸为 400*800，可拖动排序，最多上传9张</div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>

            <div class="foot-btn">
                <el-form-item>
                    <el-button type="primary" @click="submitFormData">立即发布</el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
            </div>

        </el-form>
    </div>
</template>

<script>
import * as api from '@/api/product/attr'
import { add_spu, spu_info } from '@/api/product/spu'
import categoryGroup from '@/components/CategoryGroup'
import categorySelector from '@/components/CategorySelector'
import brandSelector from '@/components/BrandSelector'
import spuCategoryAttrs from '@/components/SpuCategoryAttrs'
import imgsUpload from '@/components/ImgsUpload'
import imgUpload from '@/components/ImgUpload'
import skuBlock from '@/components/Sku/SkuBlock'
import skuTable from '@/components/Sku/SkuTable'
export default {
    //import引入组件才能使用
    components: { categoryGroup, categorySelector, brandSelector, spuCategoryAttrs, imgsUpload, imgUpload, skuBlock, skuTable },
    props: {},
    data() {
        return {
            resourcesUrl: process.env.VUE_APP_MINIO_API,
            dataForm: {
                spuId: this.$route.query.spuId || null, // 商品id
                categoryId: null, // 分类id
                shopCategoryId: null, // 店铺分类id
                name: '', // 商品名称
                sellingPoint: '', // 商品卖点
                brandId: 0, // 品牌id（非必选）
                imgUrls: '', // 轮播图 多个图片逗号分隔
                isCompose: 0, // 是否为组合商品0普通商品，1组合商品
                mainImgUrl: '', // 商品主图
                hasSkuImg: 0, // sku是否含有图片 0无 1有
                seq: null, // 商品排序（非必填）
                spuAttrValues: [], // 商品属性值列表
                detail: '', // 详情信息（非必填）
                skuList: [], // sku列表
                totalStock: 0 // 商品总库存
            },
            brandName: '', // 品牌名称
            brandImgUrl: '', // 品牌logo
            brandSelectVisible: false, // 品牌选择组件显隐
            basicAttrs: [], // 基本属性列表
            salesAttrs: [], // 销售属性列表
            originalSalesAttrs: [], // 起初的(不变的)销售属性
            categorySelectorVisible: false, // 分类选择器弹窗显隐
            shopcategorySelectorVisible: false, // 店铺分类选择器弹窗显隐
            selectedCategorys: [], // 选中的平台分类
            selectedShopCategorys: [], // 选中的店铺分类
            showCategorySelectBtn: true, // '选择分类'按钮显隐
            showShopCategorySelectBtn: true, // 店铺'选择分类'按钮显隐
            spuAttrValueList: [], // 商品基本属性值列表
            value: null,
            rules: {
                name: [
                    { required: true, message: '请输入商品标题', trigger: 'blur' }
                ],
                sellingPoint: [
                    { required: true, message: '请输入商品卖点', trigger: 'blur' }
                ],
                seq: [
                    { required: true, message: '请输入商品排序', trigger: 'blur' }
                ]
            },
            originalSpuAttrValueList: [], // 基本属性回显原数据
        }

    },
    // 计算属性
    computed: {},
    // 监听data中的数据变化
    watch: {
        'dataForm.skuList': {
            handler(val) {
                this.dataForm.totalStock = 0
                val.forEach(item => {
                    this.dataForm.totalStock += item.stock
                })
            },
            deep: true
        },
    },
    // 方法集合
    methods: {
        //选择/修改分类
        selectOrReviseCategory(key) {
            console.log('选择分类key:', key)
            this.selectKey = key
            if (key == 'platform') {
                this.categorySelectorVisible = true
                this.$nextTick(() => {
                    this.$refs.categorySelector.init(key)
                })
            } else if (key == 'shop') {
                this.shopcategorySelectorVisible = true
                this.$nextTick(() => {
                    this.$refs.shopCategorySelector.init(key)
                })
            }
        },
        getCategorySelected(selectedCategorys, categoryId) {
            console.log('平台分类子组件数据：selectedCategorys:', selectedCategorys, 'categoryId:', categoryId)
            this.categorySelectorVisible = false
            this.selectedCategorys = selectedCategorys
            this.dataForm.categoryId = categoryId
            api.list_base({ categoryId }).then(res => {
                this.basicAttrs = res.data
            })
            api.list_sale({ categoryId }).then(res => {
                this.originalSalesAttrs = res.data
                this.$nextTick(() => {
                    this.$refs.skuBlock.init()
                })

            })

        },
        getShopCategorySelected(selectedCategorys, categoryId) {
            console.log('店铺分类子组件数据：selectedCategorys:', selectedCategorys, 'categoryId:', categoryId)
            this.shopcategorySelectorVisible = false
            this.selectedShopCategorys = selectedCategorys
            this.dataForm.shopCategoryId = categoryId
        },
        //打开品牌选择器
        brandSelectHandle() {
            if (!this.dataForm.categoryId) {
                return
            }
            const brands = []
            brands.push({ brandId: this.dataForm.brandId })
            this.brandSelectVisible = true
            this.$nextTick(() => {
                this.$refs.brandSelect.init(brands, this.dataForm.categoryId)
            })
        },
        // 选择品牌
        selectBrand(brands) {
            if (brands) {
                this.brandImgUrl = brands[0].brandImgUrl
                this.dataForm.brandId = brands[0].brandId
                this.brandName = brands[0].brandName
                // 删除多余参数
                this.dataForm.brand = undefined
            }
        },
        /**
     * 基本属性数据
     */
        getValueOfBasicAttrs(attrsList, attrs, st) {
            const originalSpuAttrValueList = this.originalSpuAttrValueList
            const spuAttrValueList = this.spuAttrValueList
            const spuAttrValue = {}
            if (this.dataForm.spuId) { // 回显
                originalSpuAttrValueList.forEach((item, index) => {
                    if (item.attrId === attrs.attrId) {
                        attrs.spuAttrValueId = item.spuAttrValueId
                        spuAttrValue.spuAttrValueId = attrs.spuAttrValueId
                    }
                })
            }
            // 获取基本属性子组件返回数据
            spuAttrValue.attrId = attrs.attrId
            spuAttrValue.attrName = attrs.name
            if (st === 0) { // 下拉选择
                attrs.attrValues.some(attr => {
                    if (attrs.attrValue === attr.attrValueId) {
                        spuAttrValue.attrValueId = attrs.attrValue
                        spuAttrValue.attrValueName = attr.value
                        spuAttrValueList.push(spuAttrValue)
                        return true
                    }
                })
            }
            if (st === 1) { // 输入框
                spuAttrValue.attrValueId = ''
                spuAttrValue.attrValueName = attrs.attrValue
                if (attrs.searchType === 1 && !attrs.attrValue) {
                    this.$message({
                        message: '当前属性为必填属性，请填写属性值！',
                        duration: 1500
                    })
                    return
                } else {
                    spuAttrValueList.push(spuAttrValue)
                }
            }
            this.dataForm.spuAttrValues = spuAttrValueList
        },
        submitFormData() {
            let data = JSON.parse(JSON.stringify(this.dataForm))
            data.skuList.forEach(item => {
                item.skuId = null
            })
            console.log("submitFormData", data)
            add_spu(data).then(res => {
                this.$message({
                    message: '添加成功',
                    type: 'success'
                })
                // this.$router.push({ name: "product_list" })
            })
        },
        resetForm() {
            this.$refs.dataForm.resetFields()
        },
    },
    // 生命周期，创建完成时（可以访问当前this实例）
    created() {
        this.spuId = this.$route.params.id
        if (this.spuId) {
            console.log("编辑商品", this.spuId)
            spu_info(this.spuId).then(res => {
                this.dataForm = res.data
                this.brandName = res.data.brand.name
                this.brandImgUrl = res.data.brand.imgUrl
                this.selectedCategorys = [res.data.category]
                this.selectedShopCategorys = [res.data.shopCategory]
                this.basicAttrs = res.data.spuAttrValues
            })
        } else {
            console.log("新增商品")
        }
    },
    // 生命周期：挂载完成时（可以访问DOM元素）
    mounted() {

    },
    beforeCreate() { },//生命周期：创建之前
    beforeMount() { },//生命周期：挂载之前
    beforeUpdate() { },//生命周期：更新之前
    updated() { },//生命周期：更新之后
    beforeDestroy() { },//生命周期：销毁之前
    destroyed() { },//生命周期：销毁完成
    activated() { },//如果页面有keep-alive缓存功能，这个函数会触发执行
}
</script>
<style scoped lang="scss">
.mod-prod-info.release-goods {
    color: #606266;

    .el-radio__input.is-checked .el-radio__inner,
    .el-checkbox__input.is-checked .el-checkbox__inner {
        border-color: #02a1e9;
        background: #02a1e9;
    }

    .el-radio__input.is-checked+.el-radio__label,
    .el-checkbox__input.is-checked+.el-checkbox__label {
        color: #02a1e9;
    }

    .el-checkbox__input.is-disabled+span.el-checkbox__label {
        color: #aaabac;
    }

    .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
        background-color: #f2f6fc;
        border-color: #dcdfe6;
    }

    .star::before {
        // *样式
        content: "*";
        color: #ff4949;
        margin-right: 4px;
    }

    // 三角形样式
    .stars-icon {
        display: inline-block;
        width: 12px;
        height: 8px;
    }

    .stars-icon::before {
        position: absolute;
        content: "";
        width: 0;
        height: 0;
        border-left: 4px solid transparent;
        border-right: 4px solid transparent;
        border-bottom: 8px solid#ff7300;
    }

    .title {
        max-width: 1200px;
        padding: 0 20px;
        font-weight: bold;
        font-size: 16px;
        height: 50px;
        line-height: 50px;
    }

    .info-box {
        max-width: 1200px;
        margin: 0 auto;
        border: 1px solid #eee;
        margin-bottom: 45px;

        .part-content {
            .prohibit {
                // 禁止点击
                cursor: not-allowed;
            }

            // 品牌
            .brand {
                display: flex;
                align-items: center;

                .brand-img {
                    display: inline-block;
                    margin-right: 6px;
                    width: auto;
                    max-width: 60px;
                    height: auto;
                    max-height: 40px;
                }

                .br {
                    margin-right: 20px;
                }

                .el-button--text {
                    color: #02a1e9;
                }

                .gray {
                    color: #bcbcbc;
                }

                .sel-brand.gray:hover {
                    cursor: not-allowed;
                }
            }

            padding: 20px;

            .part-tit {
                margin-bottom: 20px;

                .part-tit-num {
                    color: #02a1e9;
                    font-size: 25px;
                    font-style: italic;
                    /* 斜体 */
                }

                .part-tit-name {
                    font-size: 15px;
                    margin: 0 10px;
                }
            }

            /* part内容 */
            .el-form-item__label {
                padding-right: 15px;
            }

            .warning {
                display: inline-block;
                color: #e43130;
            }

            .part-form-div {
                display: flex;
                align-items: top;
                font-size: 14px;
                margin-bottom: 22px;

                .part-form-item-tit {
                    width: 120px;
                    min-width: 120px;
                    text-align: right;
                    padding-right: 14px;
                    line-height: 36px;
                    box-sizing: border-box;
                }

                .part-tips {
                    color: #999;
                    font-size: 13px;
                    line-height: 36px;
                }

                .part-form-item {
                    width: 100%;

                    // 分类
                    .classify-show {
                        line-height: 36px;

                        .classify {
                            display: inline-block;
                            // min-width: 200px;
                            line-height: 36px;
                            padding: 0;
                            border: 0;
                            margin-right: 20px;
                        }

                        .change-classify {
                            color: #02a1e9;
                            cursor: pointer;
                            margin-left: 0;
                        }
                    }

                    // 轮播图
                    .banner-tips {
                        margin-top: 10px;
                        font-size: 13px;
                        color: #999;
                    }
                }

                // 新增销售属性
                .add-new-attr {
                    margin-bottom: 20px;

                    .el-form-item {
                        margin-bottom: 0;
                    }
                }

                /* 价格及库存 */
                .setup-spec {
                    width: 100%;
                    background: #fafafa;
                    padding: 15px;

                    .imp-tips {
                        font-size: 13px;
                        color: #ec6b01;
                        margin-bottom: 5px;
                    }

                    .sku-table {
                        margin-top: 15px;

                        .el-table th.is-leaf {
                            background: #f7f7f7;
                        }
                    }
                }
            }

            /* 属性面板 */
            .text {
                position: relative;
                min-width: 200px;
                color: #888;
                line-height: 36px;

                .stars-icon::before {
                    // top: 15px;
                    margin-left: 2px;
                }
            }

            .attr-type {
                p {
                    display: inline-block;
                    margin: 0;
                    color: #606266;
                    font-size: 13px;
                }

                p.attr-tit {
                    margin-right: 20px;
                }
            }

            // 运费设置
            .part-form-logistics {
                .log-tem-tips {
                    font-size: 13px;
                    color: #999;
                    margin-top: 5px;
                }

                .lb {
                    display: inline-block;
                    margin-left: 20px;

                    .vertical {
                        display: inline-block;
                        width: 1px;
                        height: 10px;
                        background: #000;
                        margin: 0 6px;
                    }
                }
            }
        }

        .part-content:not(:first-child) {
            border-top: 1px solid #eee;
        }
    }

    /* 脚部按钮 */
    .foot-btn {
        position: fixed;
        bottom: 0;
        width: 1034px;
        padding: 15px 0;
        display: flex;
        justify-content: center;
        background: #fff;
        // border-top: 1px solid #ddd;
        box-shadow: 0 -2px 3px rgba(139, 139, 139, 0.1);
        z-index: 111;

        .el-form-item {
            margin-bottom: 0;
        }
    }
}
</style>